package com.klm.easymq.core.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.klm.easymq.config.EasyMqProperties;
import com.klm.easymq.core.MessageSerializer;
import lombok.extern.slf4j.Slf4j;

/**
 * JSON消息序列化器实现
 */
@Slf4j
public class JsonMessageSerializer implements MessageSerializer {
    
    private final ObjectMapper objectMapper;
    
    public JsonMessageSerializer(EasyMqProperties.Json jsonConfig) {
        this.objectMapper = new ObjectMapper();
        // 根据配置设置ObjectMapper
        if (!jsonConfig.isIncludeNull()) {
            this.objectMapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL);
        }
        // 设置日期格式
        this.objectMapper.setDateFormat(new java.text.SimpleDateFormat(jsonConfig.getDateFormat()));
    }
    
    @Override
    public byte[] serialize(Object message) {
        try {
            return objectMapper.writeValueAsBytes(message);
        } catch (Exception e) {
            log.error("JSON序列化失败: {}", message, e);
            throw new RuntimeException("JSON序列化失败", e);
        }
    }
    
    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        try {
            return objectMapper.readValue(data, clazz);
        } catch (Exception e) {
            log.error("JSON反序列化失败: {}", new String(data), e);
            throw new RuntimeException("JSON反序列化失败", e);
        }
    }
    
    @Override
    public String getType() {
        return "json";
    }
} 